package cc.fine.svc.main.service.impl.tbl;

import cc.fine.svc.main.bean.dto.UserInfoDto;
import cc.fine.svc.main.bean.es.UserSearchEsEntity;
import cc.fine.svc.main.bean.es.UserUpdateEsEntity;
import cc.fine.svc.main.bean.po.TblUser;
import cc.fine.svc.main.bean.vo.UserVo;
import cc.fine.svc.main.mapper.TblUserMapper;
import cc.fine.svc.main.service.tbl.TblUserService;
import cc.fine.svc.main.utils.EsUtil;
import cc.fine.svc.main.utils.SecurityUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyihe
 * @since 2023-10-25
 */
@Service
public class TblUserServiceImpl extends ServiceImpl<TblUserMapper, TblUser> implements TblUserService {

    @Autowired
    private EsUtil esUtil;

    @Autowired
    private SecurityUtils securityUtils;

    @Override
    public UserInfoDto getInfo(String userId) {
        return baseMapper.selectUserInfo(userId);
    }

    @Override
    public List<Map<String, Object>> search(String keyword, Integer page, Integer limit) {
        List<Map<String, Object>> res;
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder
                .query(
                        QueryBuilders
                                .multiMatchQuery(keyword,
                                        "fineId.keyword", "username")
                );

        try {
            res = esUtil.searchListData(TblUserService.User_Search_Es_Index, builder, limit, page * limit, "", "", "");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return res;
    }

    @Override
    public List<TblUser> getByIdBatch(List<String> userIds) {
        if (userIds.isEmpty()) return new ArrayList<>();

        List<TblUser> res = baseMapper.getByIdBatch(userIds);
        if (res == null) res = new ArrayList<>();
        return res;
    }

    @Override
    public void updateInfo(String userId, UserUpdateEsEntity entity) {
        TblUser user = getById(userId);
        BeanUtils.copyProperties(entity, user);

        updateById(user);

        // 更新 es 数据
        try {
            esUtil.updateDataById(entity, TblUserService.User_Search_Es_Index, userId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
